package personal.emailsender.shared.verifier;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import personal.emailsender.server.exception.InvalidFieldException;
import personal.emailsender.shared.data.EmailContent;

public class EmailContentFieldVerifier {

	private EmailContentFieldVerifier() {}

	public static void verify(EmailContent contentFromUser) throws InvalidFieldException {
		verifyEmailInput("Sender Email", contentFromUser.getSenderEmail());
		verifyEmailInputs("Receiver Emails", contentFromUser.getReceiverEmails());
	}

	protected static void verifyEmailInputs(String fieldDisplay, Iterable<String> emailStrings)
			throws InvalidFieldException {
		for (String emailString : emailStrings) {
			verifyEmailInput(fieldDisplay, emailString);
		}
	}

	protected static void verifyEmailInput(String fieldDispaly, String emailString)
			throws InvalidFieldException {
		if (emailString == null || emailString.isEmpty()) {
			throw new InvalidFieldException(fieldDispaly);
		}
		// Use java email package to convert email string to Internet address to verify address
		try {
			new InternetAddress(emailString);
		} catch (AddressException e) {
			throw new InvalidFieldException(fieldDispaly);
		}
	}
}
